package com.th.system.listen;

import com.th.common.constant.AuthConstants;
import com.th.common.enums.AuthType;
import com.th.common.enums.ExamineResultStatus;
import com.th.system.domain.UsQuaVerify;
import com.th.system.domain.vo.EmailVo;
import com.th.system.service.EmailService;
import com.th.system.service.ISysQuaVerifyService;
import com.th.system.service.ISysUserService;
import com.th.system.service.UsUserService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author ErrorRua
 * @date 2023/06/25
 * @description:
 */
@Component
public class AuthMessageListener {

    @Autowired
    private ISysQuaVerifyService sysQuaVerifyService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private UsUserService usUserService;

    @RabbitListener(queues = AuthConstants.AUTH_MAIL_MESSAGE_QUEUE)
    public void authInternalMessageHandler(String id){
        UsQuaVerify quaVerify = sysQuaVerifyService.getById(id);

        EmailVo emailVo = buildEmailVo(quaVerify);

        emailService.sendEmail(emailVo);

    }


    /**
     * 构建邮件对象
     * @param quaVerify
     * @return
     */
    private EmailVo buildEmailVo(UsQuaVerify quaVerify) {
        // 获取用户邮箱
        Long userId = quaVerify.getUserId();
        String email = usUserService.getById(userId).getUserEmail();

        EmailVo emailVo = new EmailVo();
        emailVo.setEmail(email);

        AuthType authType = AuthType.of(quaVerify.getAuthType());

        if (Objects.equals(quaVerify.getExamineResultStatus(), ExamineResultStatus.PASS.getCode())) {
            emailVo.setSubject(authType.getName() + "认证通过通知");
            emailVo.setText("您的认证申请已通过");
        } else if (Objects.equals(quaVerify.getExamineResultStatus(), ExamineResultStatus.UNPASS.getCode())) {
            emailVo.setSubject(authType.getName() + "认证未通过通知");
            emailVo.setText("您的认证申请未通过，原因：" + quaVerify.getExamineResultMessage());
        }

        return emailVo;
    }
}
